#  Copyright (c) 2025-2025 Huawei Technologies Co., Ltd.
#  #
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#  #
#  http://www.apache.org/licenses/LICENSE-2.0
#  #
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

"""
导入相关依赖
"""
import os
import torch
import torch_npu
import torch.utils.data
from transformers import AutoTokenizer, AutoModelForCausalLM

from modelslim.pytorch.llm_ptq.anti_outlier import AntiOutlier, AntiOutlierConfig
 
SEQ_LEN_OUT = 32
 
torch.npu.set_compile_mode(jit_compile=False)
option = {}
option["NPU_FUZZY_COMPILE_BLACKLIST"] = "ReduceProd"
torch.npu.set_option(option)

"""
导入相关模型
"""
LOAD_PATH = "/data1/Qwen2-7B"
LOAD_PATH = f"{os.environ['PROJECT_PATH']}/resource/llm_ptq/Qwen2.5-7B-Instruct/"
tokenizer = AutoTokenizer.from_pretrained(
    pretrained_model_name_or_path=LOAD_PATH,
    trust_remote_code=True
)
tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained(
    pretrained_model_name_or_path=LOAD_PATH,
    torch_dtype='auto',
    trust_remote_code=True,
).npu()
 
 
calib_list = ["Where is the capital of China?",
              "Please make a poem:",
              "I want to learn python, how should I learn it?",
              "Please help me write a job report on large model inference optimization:",
              "What are the most worth visiting scenic spots in China?"]
def get_calib_dataset(tokenizer, calib_list):
    calib_dataset = []
    for calib_data in calib_list:
        inputs = tokenizer([calib_data], return_tensors='pt')
        print(inputs)
        calib_dataset.append(
            [
                inputs.data['input_ids'].to(model.device),
                inputs.data['attention_mask'].to(model.device)
            ]
        )
    return calib_dataset
 
dataset_calib = get_calib_dataset(tokenizer, calib_list)
 
keys = ['.o_proj']
anti_disable_names = []
for name, mod in model.named_modules():
    if isinstance(mod, torch.nn.Linear):
        for key in keys:
            if key in name:
                anti_disable_names.append(name)

"""
对于linear算子中的激活值如果有表示范围过大，或者"尖刺"的异常值过多，
需要使用anti outlier功能，使用方法如下
"""
with torch.no_grad():
    anti_config = AntiOutlierConfig(
        anti_method='m6',
        dev_type='npu',
        dev_id=model.device.index,
        disable_anti_names=anti_disable_names,
        flex_config={'alpha': 0.75,
                    'beta': 0.1},
    )
    anti_outlier = AntiOutlier(
        model,
        calib_data=dataset_calib,
        cfg=anti_config,
    )
    anti_outlier.process()
    print('The m6 anti-outlier process has been completed by auto-search!')
 
model = AutoModelForCausalLM.from_pretrained(
    pretrained_model_name_or_path=LOAD_PATH,
    torch_dtype='auto',
    trust_remote_code=True,
).npu()
 
with torch.no_grad():
    anti_config = AntiOutlierConfig(
        anti_method='m6',
        dev_type='npu',
        dev_id=model.device.index,
        disable_anti_names=anti_disable_names,
    )
    anti_outlier = AntiOutlier(
        model,
        calib_data=dataset_calib,
        cfg=anti_config,
    )
    anti_outlier.process()
    print('The m6 anti-outlier process has been completed by optimizing alpha-beta parameters!')